const jwt = require('jsonwebtoken');
const User = require('../models/user');
const JWT_SECRET = 'long';

class AuthService {
  // 生成JWT token
  static generateToken(user, platform = 'h5') {
    const expiresIn = platform === 'h5' ? '7d' : '6h';  // h5端7天，pc端6小时
    
    return jwt.sign(
      {
        id: user._id,
        username: user.username,
        role: user.role,
        platform
      },
      JWT_SECRET,
      { expiresIn }
    );
  }

  // 验证用户凭证
  static async verifyCredentials(username, password, role = null) {
    const query = { username };
    if (role) {
      query.role = role;
    }
    
    const user = await User.findOne(query);
    
    if (!user) {
      throw new Error('用户不存在');
    }

    const isValid = await user.comparePassword(password);
    if (!isValid) {
      throw new Error('密码错误1');
    }

    return user;
  }

  // 用户登录
  static async login(username, password, role = null, platform = 'h5') {
    try {
      const user = await this.verifyCredentials(username, password, role);
      const token = this.generateToken(user, platform);

      return {
        token,
        user: {
          id: user._id,
          username: user.username,
          role: user.role,
          email: user.email,
          nickname: user.nickname,
          avatar: user.avatar
        }
      };
    } catch (error) {
      throw error;
    }
  }

  // 用户注册
  static async register(userData, defaultRole = 'h5') {
    try {
      // 检查用户名是否已存在
      const existingUser = await User.findOne({ username: userData.username });
      if (existingUser) {
        throw new Error('用户名已存在');
      }

      // 设置默认角色
      if (!userData.role) {
        userData.role = defaultRole;
      }

      // 验证角色是否有效
      if (!['admin', 'operator', 'h5'].includes(userData.role)) {
        throw new Error('无效的用户角色');
      }

      // 创建新用户
      const user = new User(userData);
      await user.save();

      const token = this.generateToken(user);

      return {
        token,
        user: {
          id: user._id,
          username: user.username,
          role: user.role,
          email: user.email,
          nickname: user.nickname,
          avatar: user.avatar
        }
      };
    } catch (error) {
      throw error;
    }
  }

  // 验证token
  static verifyToken(token) {
    try {
      return jwt.verify(token, JWT_SECRET);
    } catch (error) {
      throw new Error('无效的token');
    }
  }
}

module.exports = AuthService; 